package com.atguigu.web;

import com.atguigu.pojo.impl.Book;
import com.atguigu.pojo.impl.Cart;
import com.atguigu.pojo.impl.CartItem;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WenUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CartServlet extends BaseServlet{
    BookService bookService = new BookServiceImpl();

    /**
     * 添加商品到购物车
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void addItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = WenUtils.parseInt(request.getParameter("id"),0);
        Book book = bookService.queryBookById(id);
        CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null){
            cart = new Cart();
            request.getSession().setAttribute("cart",cart);
        }
        cart.addItem(cartItem);
        request.getSession().setAttribute("lastName",cartItem.getName());
        response.sendRedirect(request.getHeader("Referer"));
    }
    protected void deleteItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = WenUtils.parseInt(request.getParameter("id"),0);
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null){
            cart.deleteItem(id);
            response.sendRedirect(request.getHeader("Referer"));
        }

    }
    protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart != null){
            cart.clear();
            response.sendRedirect(request.getHeader("Referer"));
        }
    }
    protected void updateCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        int id = WenUtils.parseInt(request.getParameter("id"),0);
        int count = WenUtils.parseInt(request.getParameter("count"),1);
        if(cart != null){
            cart.updateCount(id,count);
            response.sendRedirect(request.getHeader("Referer"));
        }
    }
}
